package com.yishu.servlet;

import com.yishu.entity.Book;
import com.yishu.Dao.BookDao;
import com.yishu.Dao.UserDao;
import com.yishu.entity.User;
import com.yishu.util.DBConnection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.util.List;

public class LoginServlet extends HttpServlet {

    DBConnection dbConnection = new DBConnection();
    UserDao userDao = new UserDao();
    BookDao bookDao = new BookDao();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);

        try {
            Connection connection = dbConnection.getCon();
            User currentUser = userDao.login(connection, user);
            dbConnection.closeCon(connection);

            if (currentUser != null) {

                int status = userDao.showStatus(connection, user);

                if (status == 1) {
                    req.setAttribute("result", "账号已被冻结!");
                    req.getRequestDispatcher("userLogin.jsp").forward(req, resp);
                } else {
                    req.setAttribute("result", "登录成功!");
                    session.setAttribute("userId", currentUser.getUserId());

                    connection = dbConnection.getCon();
                    List<Book> bookList = bookDao.showAllBook();

                    req.setAttribute("bookList", bookList);
                    req.getRequestDispatcher("index.jsp").forward(req, resp);
                }
            } else {
                req.setAttribute("result", "账号或密码错误,登录失败!");
                req.getRequestDispatcher("userLogin.jsp").forward(req, resp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
